from imports import *

# trying out different allowable differences
RMS_MAXIMUM_DIFFERENCE = 15

#http://stackoverflow.com/questions/1927660/compare-two-images-the-python-linux-way
# compare two image objects
# condition: Image is already imported
def compare_images(image1, image2):
    import Image
    import math
    import operator
    h1 = image1.histogram()
    h2 = image2.histogram()
    rms = math.sqrt(reduce(operator.add, map(lambda a,b: (a-b)**2, h1, h2))/len(h1))
    return rms

# find the block type from a set of block chunks of type Image
# chunk must use image_load for transparency
def get_block_type(chunk, block_images):
    matches = []
    histogram = chunk.histogram()
    for block in block_images:
        if compare_images(chunk, block) < RMS_MAXIMUM_DIFFERENCE:
            matches.append((block,compare_images(chunk,block)))
    if len(matches) > 0:
        return sorted(matches, key=lambda match:match[1])[0][0].filename
    return False

# requires Image object
# not sure if works or even needed
def get_chunk(image, height, width):
    image_x, image_y = image.size
    for i in range(image_y / height):
        for j in range(image_x / width):
            box = (j * width, i * height, (j+1) * width, (i+1)*height)
            return image.crop(box).convert()
        
def parse_level(image, height, width, out_file, img_name, block_images):
    out_file = open(out_file, 'w')
    out_image = Image.new('RGB',(image.size))
    image_x, image_y = image.size
    print image_x,image_y
    done = 0
    total = image_x / width * image_y / height
    for i in range(16,image_y,height):
        for j in range(0,image_x,width):
            box = (j,i,j+width,i+height)
            chunk = image.crop(box).convert()
            block_type = get_block_type(chunk, block_images)
            if block_type:
                out = Image.open(block_type)
                block_type = block_type.split('/')[-1] # get the filename only
                out.save("data/%d,%d %s.bmp" % (box[0],box[1],block_type),'BMP')
                out_file.write("%d,%d,1,1\n" % (j, i))
                for px in range(width):
                    for py in range(height):
#                        out_image.putpixel((box[0]+px,box[1]+py),chunk.getpixel((px,py)))
                        out_image.putpixel((box[0]+px,box[1]+py),out.getpixel((px,py)))
            done += 1
            if done % 50 == 0: # print progress every 50 blocks
                print "parsed %d%%" % (done/float(total) * 100)
    out_image.save(img_name)
    print "parsing of %d chunks complete." % done

def main():
    # block directory should be passed in as sys.argv[1]
    block_dir = sys.argv[1]
    block_paths = os.listdir(block_dir)
    block_images = [image_load2(block_dir + path) for path in block_paths]
    print(block_paths)
    print(len(block_images))
    for block in block_images:
        print(block.filename)
    level1_map = image_load2("mario-1-1.gif")
    level2_map = image_load2("mario-1-2.gif")
    parse_level(level1_map, 32, 32, "test1.txt","OUT_IMAGE_GENERATED1.BMP",block_images)
    parse_level(level2_map, 32, 32, "test2.txt","OUT_IMAGE_GENERATED2.BMP",block_images)

if __name__ == "__main__":
    main()
